package com.second.app.paixu;


/**
 * 冒泡排序
 */

public class BubbleSortPractice {

    public static void main(String[] args) {

        int[] arr = {4, 2, 10, 66, 100, 9, 18};
        bubbleSort(arr);
        System.out.println("====冒泡排序结果打印 由小到大排列=====");
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]+" ");
        }

        int[] arr_ = {4, 2, 10, 66, 100, 9, 18};
        bubbleSortDesc(arr_);
        System.out.println("====冒泡排序结果打印 由大到小排列=====");
        for (int i = 0; i < arr_.length; i++) {
            System.out.println(arr_[i]+" ");
        }


    }

    public static void bubbleSort(int[] arr) {
        int n = arr.length;
        for (int i = 0; i < n - 1; i++) {
            for ( int j = 0; j < n - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }

            }
        }
    }
    public static void bubbleSortDesc(int[] arr) {
        int n = arr.length;
        boolean swap = false;
        for (int i = 0; i < n - 1; i++) {
            for ( int j = 0; j < n - 1 - i; j++) {
                if (arr[j] < arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                    swap =true;
                }
            }
            if (!swap){
                break;
            }
        }
    }
}
